package com.component.api.utils;

import cn.hutool.core.util.StrUtil;
import com.component.api.model.UnifiedType;

import java.sql.Types;

/**
 * 描述：
 * 字段类型转换
 * @author xianggj
 * @Date 2021/12/3 17:37
 **/
public class TypesUtils {


    /**
     * 统一类型
     * 将Types的模糊类型在归类
     *  归纳为
     * @param b
     * @return
     */
    public static UnifiedType unifiedType(int b) {
        if (b == Types.VARCHAR || b == Types.CHAR || b == Types.LONGNVARCHAR) {
            return UnifiedType.STRING;
        } else if (b == Types.INTEGER || b == Types.SMALLINT || b == Types.TINYINT) {
            return UnifiedType.INTEGER;
        } else if (b == Types.BIGINT) {
            return UnifiedType.LONG;
        } else if (b == Types.FLOAT || b == Types.REAL || b == Types.DOUBLE || b == Types.NUMERIC || b == Types.DECIMAL) {
            return UnifiedType.DOUBLE;
        } else if (b == Types.DATE || b == Types.TIME || b == Types.TIMESTAMP || b == Types.TIME_WITH_TIMEZONE || b == Types.TIMESTAMP_WITH_TIMEZONE) {
            return UnifiedType.DATETIME;
        } else {
            return UnifiedType.OTHER;
        }
    }

    public static UnifiedType unifiedType(String typeInfo) {
        return unifiedType(typeStrToInt(typeInfo));
    }

    /**
     * 字符串类型转Int
     */
    public static int typeStrToInt(String typeInfo) {
        typeInfo = StrUtil.isBlank(typeInfo) ? "string" : typeInfo.toLowerCase();
        switch (typeInfo) {
            case "int":
            case "integer":
            case "int2":
            case "int4":
            case "smallint":
            case "tinyint":
                return Types.INTEGER;
            case "int8":
            case "bigint":
                return Types.BIGINT;
            case "float":
            case "float2":
            case "float4":
                return Types.FLOAT;
            case "float8":
            case "double":
            case "number":
                return Types.DOUBLE;
            case "time":
                return Types.TIME;
            case "date":
                return Types.DATE;
            case "datetime":
            case "timestamp":
            case "timestamp(6)":
                return Types.TIMESTAMP;
            case "boolean":
            case "bool":
                return Types.BOOLEAN;
            case "byte":
                return Types.BINARY;
            case "short":
                return Types.SMALLINT;
            case "character":
            case "char":
                return Types.CHAR;
            case "decimal":
            case "bigdecimal":
                return Types.DECIMAL;
            default:
                return Types.VARCHAR;
        }
    }
}
